package cn.topkinson.rocketmq.seckill.listener;

import cn.topkinson.rocketmq.seckill.common.RedisConstant;
import cn.topkinson.rocketmq.seckill.common.RocketConstant;
import cn.topkinson.rocketmq.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Author huangzihao
 * @Date 2021/1/18 14:31
 */
@Slf4j
@Component
@RocketMQTransactionListener(txProducerGroup = RocketConstant.GROUP_ORDER_TX)
public class OrderTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @PostConstruct
    public void init(){
        redisTemplate.opsForValue().set(RedisConstant.SECKILL_STOCK_NUM,"10");
        log.info("初始化库存数量：10");
    }

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            log.info("====处理事务消息开始====");
            //查询库存,有库存commit消息，没库存rollback消息
            String stock_num_str = (String)redisTemplate.opsForValue().get(RedisConstant.SECKILL_STOCK_NUM);
            Integer stock_num = Integer.valueOf(stock_num_str);
            if (stock_num!=null && stock_num>0){
                Long increment = redisTemplate.opsForValue().increment(RedisConstant.SECKILL_STOCK_NUM, -1);
                log.info("有库存，消息提交，并扣减库存，当前剩余库存：{}",increment);
                return RocketMQLocalTransactionState.COMMIT;
            }else{
                log.info("无库存，消息回滚");
                return RocketMQLocalTransactionState.ROLLBACK;
            }
        }catch (Exception e){
            log.error("处理异常，回滚消息",e);
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        //查询库存,有库存commit消息，没库存rollback消息
        Integer stock_num = (Integer)redisTemplate.opsForValue().get(RedisConstant.SECKILL_STOCK_NUM);
        if (stock_num>0){
            return RocketMQLocalTransactionState.COMMIT;
        }else{
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
